﻿using System;
using System.Configuration;
using System.IO;
//using System.Net.Http;
using System.Security.Cryptography;
using System.Text;
using System.Web;

namespace VASJ.Model
{
    public class WebUtils
    {
        public static string DateTimeFormat = @"dd.MM.yyyy HH:mm:ss";

        //public static StreamContent GetContent(string file)
        //{
        //    FileStream fs = new FileStream(file, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
        //    MemoryStream memStream = new MemoryStream();
        //    fs.CopyTo(memStream);
        //    fs.Close();

        //    memStream.Seek(0, SeekOrigin.Begin);
        //    return new StreamContent(memStream);
        //}

        public static string GetMD5HashFromFile(string fileName)
        {
            try
            {
                FileStream file = new FileStream(fileName, FileMode.Open);
                MD5 md5 = new MD5CryptoServiceProvider();
                byte[] retVal = md5.ComputeHash(file);
                file.Close();

                StringBuilder sb = new StringBuilder();
                for (int i = 0; i < retVal.Length; i++)
                {
                    sb.Append(retVal[i].ToString("x2"));
                }
                return sb.ToString();
            }
            catch
            {
                throw new Exception("The file does not exist or not accessible");
            }
        }

        public static string GetMD5FromStream(Stream stream)
        {
            try
            {
                MD5 md5 = new MD5CryptoServiceProvider();
                byte[] retVal = md5.ComputeHash(stream);

                var sb = new StringBuilder();
                for (int i = 0; i < retVal.Length; i++)
                {
                    sb.Append(retVal[i].ToString("x2"));
                }
                return sb.ToString();
            }
            catch
            {
                throw new Exception("Unable to calculate md5 hash");
            }
        }

        public static string GetSiteRoot()
        {
            string port = HttpContext.Current.Request.ServerVariables["SERVER_PORT"];
            if (port == null || port == "80" || port == "443")
                port = "";
            else
                port = ":" + port;

            var protocol = HttpContext.Current.Request.ServerVariables["SERVER_PORT_SECURE"];
            if (protocol == null || protocol == "0")
                protocol = "http://";
            else
                protocol = "https://";

            var sOut = protocol + HttpContext.Current.Request.ServerVariables["SERVER_NAME"] + port + HttpContext.Current.Request.ApplicationPath;

            if (sOut.EndsWith("/"))
            {
                sOut = sOut.Substring(0, sOut.Length - 1);
            }

            return sOut;
        }

        public static bool SaveStream(Stream input, string targetPath)
        {
            try
            {
                string pth = Path.GetDirectoryName(targetPath);
                Directory.CreateDirectory(pth);
                FileStream fs = new FileStream(targetPath, FileMode.Create);

                byte[] buffer = new byte[8 * 1024];
                int len;
                input.Seek(0, SeekOrigin.Begin);
                while (true)
                {
                    len = input.Read(buffer, 0, buffer.Length);
                    if (len <= 0)
                    {
                        break;
                    }
                    fs.Write(buffer, 0, len);
                }
                fs.Close();
                return true;
            }
            catch (Exception ex)
            {
                Logger.Log.ErrorFormat("Unable to save the stream into disk", targetPath);
                Logger.Log.Error(ex.Message);
                return false;
            }
        }

        public static long GetDocSize(string path)
        {
            try
            {
                FileInfo fi = new FileInfo(path);
                return fi.Length;
            }
            catch
            {
                return 0;
            }
        }

        public static int GetConfigInt(string cfgName, int def)
        {
            try
            {
                string szDef = ConfigurationManager.AppSettings[cfgName];
                if (string.IsNullOrEmpty(szDef) == false)
                {
                    return Convert.ToInt32(szDef);
                }
                else
                {
                    return def;
                }
            }
            catch
            {
                return def;
            }
        }

    }
}